from flask import Flask
from flask.cli import FlaskGroup
from flask_migrate import Migrate

from app.extensions import db, jwt, cors
from app.routes.article_route import article_bp
from app.routes.category_route import category_bp
from app.routes.problem_route import problem_bp
from app.routes.solution_route import solution_bp
from app.routes.user_route import user_bp
from app.models.user import User
from app.models.article import Article
from app.models.problem import Problem
from app.models.statistics import Statistics
from app.utils.response import error


def create_app():
    app = Flask(__name__)
    app.config.from_object('app.config.Config')
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    cors.init_app(app)  # 处理跨域
    migrate = Migrate(app, db)

    # 注册蓝图
    app.register_blueprint(user_bp, url_prefix='/user')
    app.register_blueprint(article_bp, url_prefix='/articles')
    app.register_blueprint(category_bp, url_prefix='/categories')
    app.register_blueprint(problem_bp, url_prefix='/problems')
    app.register_blueprint(solution_bp, url_prefix='/solutions')

    # 确保在创建应用时正确初始化 CLI
    cli = FlaskGroup(create_app=create_app)
    cli.name = 'flask'
    app.cli.add_command(cli)


    return app